//
//  RecordViewController.m
//  iOS_2D_RecordPath
//
//  Created by PC on 15/8/3.
//  Copyright (c) 2015年 FENGSHENG. All rights reserved.
//

#import "RecordViewController.h"
#import "DisplayViewController.h"
#import "AMapRouteRecord.h"
#import "FileHelper.h"
#import "NKRouteRecord.h"

@interface RecordViewController()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *pathArray;

@property (nonatomic, assign) BOOL  isLocal;

@end

@implementation RecordViewController

#pragma mark - Life Cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initData];
    
    [self initView];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

- (void)initData {

    _pathArray = [NSMutableArray array];
    [_pathArray addObjectsFromArray: [FileHelper recordsArray]];
    _isLocal = YES;
    
}

- (void)initView {

    UIButton *quitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    quitButton.frame = CGRectMake(10, 30, 30, 30);
    [quitButton setImage:[UIImage imageNamed:@"quit"] forState:UIControlStateNormal];
    [quitButton addTarget:self action:@selector(quit) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:quitButton];
    
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"本地",@"远程"]];
    segment.frame = CGRectMake(0, 30, 80, 30);
    segment.NK_centerX = self.view.NK_centerX;
    segment.selectedSegmentIndex = 0;
    segment.tintColor = NKBlueColor;
    [segment addTarget:self action:@selector(selectClassTypeWithSegment:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segment];
    
    
    self.tableView = [[UITableView alloc] initWithFrame: CGRectMake(0, 64, NKScreenWidth, NKScreenHeight - 64)];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor whiteColor];

}



- (void)unZip:( NSString *) fileName {

    //源文件路径
    NSString *sourceFilePath =  [[FileHelper baseDir] stringByAppendingPathComponent:fileName];
    //目的文件路径
    NSString *destinationPath = [FileHelper baseDir] ;
    //把 sourceFilePath 这个路径下的zip包，解压到这个 destinationPath 路径下
    if ([SSZipArchive unzipFileAtPath:sourceFilePath toDestination:destinationPath]){
       
        [SVProgressHUD showSuccessWithStatus:@"解压成功"];
    }
    else {
        [SVProgressHUD showErrorWithStatus:@"解压失败"];
    }

}


- (void)selectClassTypeWithSegment:(UISegmentedControl *)segmentedControl {

    [_pathArray removeAllObjects];
    // 本地
    if (segmentedControl.selectedSegmentIndex == 0) {
        
        _isLocal = YES;
        [_pathArray  addObjectsFromArray:[FileHelper recordsArray]];
        [self.tableView reloadData];
    // 远程
    }else {
    
        _isLocal = NO;
        [[NKNetworkManager shareInstance] requestType: REQUESTTYPEGET withUrlString:NKGetZipListUrl parames:nil success:^(id  _Nullable responseObject) {
            
            NSArray *dataArray = responseObject[@"data"];
            if (![dataArray isEqual:[NSNull null]]) {
                
                [_pathArray addObjectsFromArray:dataArray];
            }
            [self.tableView reloadData];
        } failure:^(id  _Nullable error) {
            
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
            [self.tableView reloadData];
        }];
    }
}

- (void)quit {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)updateFile:( NSString *) fileName {
    
    // 先压缩
    //目的路径
    NSString *destinationPath = [[FileHelper baseDir] stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.zip",fileName]];//注意是这个是 zip 格式的后缀
    //源文件路径
    NSString *sourceFilePath = [[FileHelper baseDir] stringByAppendingPathComponent: fileName];
    //数组里可以放多个源文件，这些文件会被同一打包成压缩包，到 destinationPath 这个路径下。
    if ([SSZipArchive createZipFileAtPath:destinationPath withContentsOfDirectory:sourceFilePath]) {
        [SVProgressHUD showWithStatus:@"开始上传"];
        
        NSDictionary *parameters = @{@"name": fileName};
        [[NKNetworkManager shareInstance] uploadWithUrlString:NKUploadZipUrl parameters:parameters uploadFileUrl:[NSURL fileURLWithPath:destinationPath]  fileName:fileName progress:^
         (NSProgress * _Nullable uploadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [FileHelper deletePath:destinationPath];
            
        } failure:^(NSError * _Nullable error) {
            
            [SVProgressHUD showErrorWithStatus:@"上传失败"];
            [FileHelper deletePath:destinationPath];
            
        }];
    }
    else {
        [SVProgressHUD showErrorWithStatus:@"压缩失败"];;
    }
}

- (void)downFileWithPath:(NSDictionary *)fileDict {

    __weak typeof(self) weakSelf = self;
    // 下载地址
    NSString *downUrl = [@"http://120.27.247.37:19121" stringByAppendingPathComponent:fileDict[@"url"]];
    // 目的文件的目录路径
    NSString *destinationPath = [FileHelper baseDir];
    
    [[NKNetworkManager shareInstance] downLoadWithUrl: downUrl  parameters:nil destinationUrl:destinationPath progerss:^(NSProgress * _Nullable progress) {
        
        [SVProgressHUD showProgress:1.0 *progress.completedUnitCount / progress.totalUnitCount];
        
    } success:^(NSURL * _Nullable filePath) {
         [SVProgressHUD showWithStatus:@"开始解压"];
        //源文件路径
        NSString *sourceFilePath =  [filePath path];
        //目的文件路径
        NSString *destinationPath =[[sourceFilePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: fileDict[@"name"]];
        //把 sourceFilePath 这个路径下的zip包，解压到这个 destinationPath 路径下
        if ([SSZipArchive unzipFileAtPath:sourceFilePath toDestination:destinationPath]){
            
            [SVProgressHUD showSuccessWithStatus:@"解压成功"];
            [FileHelper deletePath:sourceFilePath];
            // 把压缩包中的json转成plist
            NSString *jsonPath = [destinationPath stringByAppendingPathComponent: [fileDict[@"name"] stringByAppendingPathExtension:@"json"]];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:jsonPath] options:NSJSONReadingMutableContainers error:nil];
            NSString *plistPath =  [destinationPath stringByAppendingPathComponent: [fileDict[@"name"] stringByAppendingPathExtension:@"plist"]];
            BOOL isSuccess = [dict writeToFile:plistPath atomically:YES];
            if (isSuccess) {
                [FileHelper deletePath:jsonPath];
            }
        }
        else {
            [SVProgressHUD showErrorWithStatus:@"解压失败"];
            [FileHelper deletePath:sourceFilePath];
        }
       
    } failure:^(NSError * _Nullable error) {
        
         [SVProgressHUD showErrorWithStatus:@"下载失败"];
        
    }];
}


#pragma mark - UITableView delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (_isLocal) {
        
        DisplayViewController *displayController = [[DisplayViewController alloc] initWithNibName:nil bundle:nil];
        
        NSString *fileName =  [NSString stringWithFormat:@"%@",self.pathArray[indexPath.row]];
        NSString *recordPath = [[FileHelper filePathWithPath:fileName] stringByAppendingPathComponent:[fileName stringByAppendingString:@".plist"]] ;
        NSDictionary *dit = [NSDictionary dictionaryWithContentsOfFile:recordPath];
        NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[FileHelper filePathWithPath:fileName] error:nil];
        @try {
            
            NKRouteRecord *record = [NKRouteRecord mj_objectWithFile:recordPath];
            [displayController setRecord: record];
            [self.navigationController pushViewController:displayController animated:YES];
            
        } @catch (NSException *exception) {
            NSLog(@"exception :%@", exception);
            [[NSFileManager defaultManager] removeItemAtPath:recordPath error:nil];
            
        } @finally {
            
        }

    }
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    __weak typeof(self) weakSelf = self;
    
    if (_isLocal) {
    
        UITableViewRowAction *updateAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"上传" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            
            tableView.editing = NO;
            NSString *fileName = [NSString stringWithFormat:@"%@",[self.pathArray objectAtIndex:indexPath.row]];
            [SVProgressHUD showWithStatus:@"开始压缩"];
            [weakSelf updateFile:fileName];

        }];
        
        
        UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            
            [FileHelper deleteFile: [NSString stringWithFormat:@"%@",[self.pathArray objectAtIndex:indexPath.row]]];
            [weakSelf.pathArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
        }];
        
        return @[updateAction,deleteAction];
        
    }else {
    
        UITableViewRowAction *downAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"下载" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            
            tableView.editing = NO;
            [weakSelf downFileWithPath:weakSelf.pathArray[indexPath.row]];
            
        }];
        
        return @[downAction];
    }
}


#pragma mark - UITableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.pathArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"recordCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIndentifier];
    }
    
    if (_isLocal) {
        
        cell.textLabel.text = [NSString stringWithFormat:@"%@",self.pathArray[indexPath.row]];
        
    }else {
    
        cell.textLabel.text = self.pathArray[indexPath.row][@"name"];
    }
    
    return cell;
}

@end
